#include <gl/freeglut.h>
#include <iostream>
using namespace std;
GLfloat rtri;
GLfloat rquad;
GLfloat points0[5][3] = { {0,1,0},{-1,-1,1},{1,-1,1},{1,-1,-1},{-1,-1,-1} };
GLfloat points1[8][3] = { {1,1,-1},{-1,1,-1},{-1,1,1},{1,1,1},{1,-1,1},{-1,-1,1},{-1,-1,-1},{1,-1,-1} };

GLfloat colors0[4][3] = { {1,0,0},{0,1,0},{0,0,1},{1,1,0} };    // 四棱锥颜色
GLfloat colors1[6][3] = { {0,1,0},{1,0.5,0},{1,0,0},{1,1,0},{0,0,1},{1,0,1} };  // 立方体颜色

int vertice0[4][3] = { {0,1,2},{0,2,3},{0,3,4},{0,4,1} };   // 四棱锥的顶点号序列，Index
int vertice1[6][4] = { {0,1,2,3},{4,5,6,7},{3,2,5,4},{7,6,1,0},{2,1,6,5},{0,3,4,7} };    // 立方体的顶点序列，index

void init()
{
    glShadeModel(GL_SMOOTH);
    glClearColor(1, 1, 1, 1);
    glClearDepth(1);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glEnable(GL_COLOR_MATERIAL);
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}

void createPytamid()
{
    glBegin(GL_TRIANGLES);
    for (int i = 0; i < 4; i++)
    {
        glColor3fv(colors0[i]);
        for (int j = 0; j < 3; j++)
        {
            int VtxId = vertice0[i][j];
            glVertex3fv(points0[VtxId]);
        }

    }
    glEnd();
    glBegin(GL_QUADS);
    glColor3f(1, 1, 1);
    for (int i = 0; i < 4; i++)
        glVertex3fv(points0[i]);
    glEnd();
}

void createCube()
{
    glBegin(GL_QUADS);
    for (int i = 0; i < 6; i++)
    {
        glColor3fv(colors1[i]);
        for (int j = 0; j < 4; j++)
        {
            int VtxId = vertice1[i][j];
            glVertex3fv(points1[VtxId]);
        }
    }
    glEnd();
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glPushMatrix();
    glTranslatef(-1.5, 0, -6);      // 平移至左侧
    glRotatef(rtri, 0, 1, 0);       // 旋转一个角度
    createPytamid();                // 创建四棱锥

    glLoadIdentity();
    glTranslatef(1.5, 0, -6);       // 平移到右侧
    glRotatef(rquad, 1, 0, 0);      // 旋转一个角度
    createCube();                   // 创建立方体
    glPopMatrix();

    rtri += 0.2;                    // 修改四棱锥的旋转角度
    rquad += 0.15;                  // 修改立方体的旋转角度
    glutSwapBuffers();
}

void reshape(int width, int height)
{
    if (height == 0)
        height = 1;
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, (GLfloat)width / height, 0.1, 100);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutInitWindowSize(600, 400);
    glutCreateWindow("Pyramid and cube");
    init();
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutIdleFunc(display);
    glutMainLoop();
}